import { reqCartList,reqDeleteCartById,reqUpdateCheckedById } from "@/api";
const actions = {
  async getCartList({commit}){
    let res = await reqCartList();
    if(res.code == 200){
      commit('CART_LIST',res.data);
    }
  },
  async deleteCartById({commit},skuId){
    let res = await reqDeleteCartById(skuId);
    if(res.code == 200){
      return "成功";
    }else {
      return Promise.reject("删除失败");
    }
  },
  async updateCartChecked({commit},{skuId,isChecked}){
    let res = await reqUpdateCheckedById(skuId,isChecked);
    if(res.code == 200){
      return "成功";
    }else {
      return Promise.reject("修改失败");
    }
  },
  deleteALLCheckedCart({dispatch,getters:{cartList:{cartInfoList}}}){
    let PromiseAll = [];
    cartInfoList.forEach(async item=>{
      let promise = item.isChecked && dispatch('deleteCartById',item.skuId);
      PromiseAll.push(promise);
    })
    return Promise.all(PromiseAll);
  },
  updateAllCheckedCart({dispatch,getters:{cartList:{cartInfoList}}},isChecked){
    let PromiseAll = [];
    isChecked = isChecked ? 1 : 0;
    cartInfoList.forEach(async item=>{
      let promise = dispatch('updateCartChecked',{skuId:item.skuId,isChecked});
      PromiseAll.push(promise);
    })
    return Promise.all(PromiseAll);
  },
};
const mutations = {
  CART_LIST(state,cartList){
    state.cartList = cartList;
  }
};
const state = {
  cartList:[],
};
const getters = {
  cartList(state){
    return state.cartList[0] || {};
  },
};
export default {
  namespaced:true,
  actions,
  mutations,
  state,
  getters,
}